/******************************************************************************************************
Copyright (C) 2018 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/
/*globals RawToMChromReporter, Application, mainWindow, NMRSpectrum, date2ISOString, mnMessage, mnError, mnInfo, File, TextStream, settings, draw, Molecule, serialization, MassItem, print, Document, gc*/
/*jslint plusplus: true, continue: true, bitwise: true*/

function RawToMChromEngine(aResFile) {
	"use strict";

	this.log = "";
	this.debugLog = Application.engine === "dbg";
	this.results = "";
	this.resFile = aResFile;
}

RawToMChromEngine.prototype.run = function (aName) {
	"use strict";

	var inputDocument, originalMSItem, workingObject, s, nSteps, peaks = [], rt = [], scan = [];

	function createMainChromatogram(aDocument, aName, aContext) {

		var i, j, t, f, MSItem, curInjInfo, curFnInfo, curTrInfo, hasDAD = false, numDADs = 0, numTICs = 0, log = '', ok, ok1, parm, parm1, ticID, ticFileName, dadID, dadFileName;
		log +=("RawToMChromEngine: Dataset Item Injection Function Type csvFile");
		try {
			for (i = 0; i < aDocument.itemCount(); i++) {
				MSItem = new MassItem(aDocument.item(i, "Mass Spectrum"));

				for (j = 0; j<MSItem.info.injections.count; j++) {
					curInjInfo = MSItem.info.injections.getItem(j);
					for(f=0; f<curInjInfo.functions.count; f++) {
						curFnInfo = curInjInfo.functions.getItem(f);
						MSItem.appendSelected = true;
						parm1 = new Object();
						parm1.injectionIndex = j;
						parm1.functionIndex = f;
						parm1.type = "TIC";
						MSItem.newChromatogram(parm1);
						MSItem.update();
						ticID = MSItem.plot(MSItem.plotsCount-1).id;
						ticFileName = aName+'_'+i+'_'+j+'_'+f+'_TIC.csv';
						ok1 = MSItem.dumpChromatogramMSSpectraToCSV(ticFileName, ticID);
						log += "\n" + MSItem.datasetFileName + " " + i + " ";
						log += j + " ";
						log += f + " ";
						log += "TIC" + " ";
						log += ticFileName;
						if (ok1!== undefined) {
							log += " " + ok1;
						}
					}

					if (curInjInfo.traces){
						hasDAD = curInjInfo.traces.hasDAD;
						if (hasDAD){
							MSItem.appendSelected = true;
							parm = new Object();
							parm.injectionIndex = j;
							parm.traceIndex = "DAD";
							parm.type = "TABS";
							MSItem.newChromatogram(parm);
							MSItem.update();
							dadID = MSItem.plot(MSItem.plotsCount-1).id;
							dadFileName = aName+'_'+i+'_'+j+'_DAD.csv';
							ok = MSItem.dumpChromatogramUVSpectraToCSV(dadFileName, dadID);
							log += "\n" + MSItem.datasetFileName + " " + i + " ";
							log += j + " ";
							log += "-" + " ";
							log += "DAD" + " ";
							log += dadFileName;
							if (ok!== undefined) {
								log += " " + ok;
							}
						}
					}
				}
			}
			aContext.writeLog(log);
			return true;
		} catch (ERR) {
			aContext.writeLog(log + ERR);
			return false;
		}
	}

	this.writeLog("RawToMChromEngine: starting ");

	if (this.debugLog) {
		this.writeLog("RawToMChromEngine: running in engine " + Application.engine);
	}

	try{
		inputDocument = mainWindow.activeDocument;
		mainWindow.activeDocument = inputDocument;
		if (inputDocument.isValid()) {
			var success = createMainChromatogram(inputDocument, this.resFile, this);
			if (success) {
				this.writeLog("RawToMChromEngine: succesfully done in " + aName);
			} else {
				this.writeLog("RawToMChromEngine: error in engine trying to run " + aName);
			}
		} else {
			this.writeLog("RawToMChromEngine: not valid input document " + aName);
		}
	} catch (ERR) {
		this.writeLog(ERR);
	}
	return;
};

RawToMChromEngine.prototype.writeLog = function (aMessage) {
	"use strict";
	var currentDate = date2ISOString(new Date()).toString().replace(new RegExp("\\:", 'g'), ".");
	this.log += ("\n[" + currentDate + "] " + aMessage);
};
